<?php
/**
 * Created by PhpStorm.
 * User: Administrator
 * Date: 2018/10/5 0005
 * Time: 08:29
 */

namespace app\common\model;


use think\Exception;

class Department extends BaseModel
{

    /**
     * 创建或者编辑部门
     * @param $param
     * @param int $id
     * @return \think\response\Json
     */
    public static function createOrUpdateDepartment($param, $id = 0) {
        try {
            if ($id > 0) {
                // 编辑
                $department = self::get($id);
                if (!$department) {
                    throw new Exception('部门不存在');
                }
                $check_department = self::where('name', '=', $param['name'])->where('id', 'neq', $id)->find();
                if ($check_department) {
                    throw new Exception('部门名已存在');
                }
                $department->save($param);
            } else {
                $check_department = self::where('name', '=', $param['name'])->find();
                if ($check_department) {
                    throw new Exception('部门名已存在');
                }
                // 添加
                self::create($param);
            }
            return return_data('success');
        } catch (Exception $e) {
            return return_data($e->getMessage(), 1);
        }
    }
}